<template>
  <div class="app-container">
    <div class="top-section-container">
      <div class="content-header">
        <h1>预约管理/<small>检查项管理</small></h1>
        <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>预约管理</el-breadcrumb-item>
          <el-breadcrumb-item>检查项管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <div class="bottom-section-container">
      <div class="filter-container box">
        <el-input
            v-model="searchText"
            placeholder="编码/名称"
            style="width: 15rem; margin-right: 0.625rem; margin-top: 10px;"
            class="filter-item"
            @keyup.enter="findPage"
        ></el-input>
        <el-button type="primary" @click="findPage">查询</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>

      <el-table
          :data="dataList"
          border
          stripe
          style="width: 100%; margin-top: 1.25rem;"
          class="datatable"
      >
        <el-table-column type="index" label="序号" align="center" width="60px"></el-table-column>
        <el-table-column prop="code" label="项目编码" align="center" width="100px"></el-table-column>
        <el-table-column prop="name" label="项目名称" align="center" min-width="120px"></el-table-column>
        <el-table-column prop="sex" label="适用性别" align="center" width="80px"> <template #default="scope">
          <span>{{ scope.row.sex == '0' ? '不限' : scope.row.sex == '1' ? '男' : '女' }}</span>
        </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" align="center" width="80px">
          <template #default="scope">
            <span>{{ scope.row.price }}</span> </template>
        </el-table-column>
        <el-table-column prop="remark" label="说明" align="center" min-width="150px"></el-table-column>
        <el-table-column prop="attention" label="注意事项" align="center" min-width="150px"></el-table-column>
        <el-table-column label="操作" align="center" width="150px">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
        ></el-pagination>
      </div>
    </div>

    <el-dialog title="新增检查项" v-model="dialogFormVisible4Add" :close-on-click-modal="false" width="35rem">
      <el-form :model="formData" :rules="rules" ref="dataAddForm" label-width="6.25rem">
        <el-form-item label="项目编码" prop="code">
          <el-input v-model="formData.code"></el-input>
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="适用性别" prop="sex"> <el-radio-group v-model="formData.sex"> <el-radio label="0">不限</el-radio>
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="formData.price"></el-input>
        </el-form-item>
        <el-form-item label="注意事项" prop="attention">
          <el-input v-model="formData.attention" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="formData.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible4Add = false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="编辑检查项" v-model="dialogFormVisible4Edit" :close-on-click-modal="false" width="35rem">
      <el-form :model="formData" :rules="rules" ref="dataEditForm" label-width="6.25rem">
        <el-form-item label="项目编码" prop="code">
          <el-input v-model="formData.code"></el-input>
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="适用性别" prop="sex"> <el-radio-group v-model="formData.sex"> <el-radio label="0">不限</el-radio>
          <el-radio label="1">男</el-radio>
          <el-radio label="2">女</el-radio>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model.number="formData.price"></el-input>
        </el-form-item>
        <el-form-item label="注意事项" prop="attention">
          <el-input v-model="formData.attention" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="formData.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
          <el-button type="primary" @click="handleEditConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

// 数据模型
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  queryString: null,
});
const dataList = ref([]); // 当前页的检查项列表
const formData = reactive({}); // 表单数据（新增/编辑）
const dialogFormVisible4Add = ref(false); // 新增弹窗显示控制
const dialogFormVisible4Edit = ref(false); // 编辑弹窗显示控制
const searchText = ref(''); // 搜索框内容

// 表单验证规则
const rules = reactive({
  code: [{ required: true, message: '项目编码为必填项', trigger: 'blur' }],
  name: [{ required: true, message: '项目名称为必填项', trigger: 'blur' }],
  sex: [{ required: true, message: '适用性别为必选项', trigger: 'change' }],
  price: [{ required: true, message: '价格为必填项', trigger: 'blur' }, { type: 'number', message: '价格必须为数字值' }],
});

// 表单引用
const dataAddForm = ref(null);
const dataEditForm = ref(null);

// 查找分页数据
const findPage = async () => {
  pagination.queryString = searchText.value; // 更新查询字符串
  try {
    const res = await axios.post('/checkitem/findPage', pagination);
    // findPage接口直接返回PageResult，不需要通过res.data.flag判断
    if (res.data) { // 检查res.data是否存在，通常成功会有数据
      dataList.value = res.data.rows; // 直接从 res.data 中获取 rows
      pagination.total = res.data.total; // 直接从 res.data 中获取 total
    } else {
      ElMessage.error('获取分页数据失败'); // 针对res.data为空的情况
    }
  } catch (error) {
    console.error('获取分页数据失败:', error);
    ElMessage.error('获取分页数据失败');
  }
};

// 处理页码改变
const handleCurrentChange = (currentPage) => {
  pagination.currentPage = currentPage;
  findPage();
};

// 处理每页显示条数改变
const handleSizeChange = (pageSize) => {
  pagination.pageSize = pageSize;
  findPage();
};

// 显示新增弹窗
const handleAdd = () => {
  dialogFormVisible4Add.value = true;
  // 重置表单数据
  Object.assign(formData, {
    code: null, name: null, sex: '0', price: null, attention: null, remark: null
  });
  // 清除验证结果
  if (dataAddForm.value) {
    dataAddForm.value.resetFields();
  }
};

// 新增确认
const handleAddConfirm = () => {
  dataAddForm.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await axios.post('/checkitem/add', formData);
        if (res.data.flag) { // 检查 R 对象的 flag 字段
          ElMessage.success(res.data.message); // 使用 R 对象的 message 字段
          dialogFormVisible4Add.value = false;
          findPage(); // 重新查询
        } else {
          ElMessage.error(res.data.message); // 使用 R 对象的 message 字段
        }
      } catch (error) {
        console.error('新增失败:', error);
        ElMessage.error('新增失败');
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入！');
      return false;
    }
  });
};

// 显示编辑弹窗并回显数据
const handleEdit = async (row) => {
  dialogFormVisible4Edit.value = true;
  try {
    const res = await axios.get('/checkitem/findById?id=' + row.id);
    if (res.data.flag) { // 检查 R 对象的 flag 字段
      Object.assign(formData, res.data.data); // 直接获取 R 对象中 data 字段的数据
    } else {
      ElMessage.error(res.data.message); // 使用 R 对象的 message 字段
    }
  } catch (error) {
    console.error('查询详情失败:', error);
    ElMessage.error('查询详情失败');
  }
};

// 编辑确认
const handleEditConfirm = () => {
  dataEditForm.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await axios.post('/checkitem/update', formData);
        if (res.data.flag) { // 检查 R 对象的 flag 字段
          ElMessage.success(res.data.message); // 使用 R 对象的 message 字段
          dialogFormVisible4Edit.value = false;
          findPage(); // 重新查询
        } else {
          ElMessage.error(res.data.message); // 使用 R 对象的 message 字段
        }
      } catch (error) {
        console.error('编辑失败:', error);
        ElMessage.error('编辑失败');
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入！');
      return false;
    }
  });
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('您确定要删除当前数据吗？', '提示', {
    type: 'warning',
  })
      .then(async () => {
        try {
          const res = await axios.delete('/checkitem/delete?id=' + row.id);
          if (res.data.flag) { // 检查 R 对象的 flag 字段
            ElMessage.success(res.data.message); // 使用 R 对象的 message 字段
            findPage(); // 重新查询
          } else {
            ElMessage.error(res.data.message); // 使用 R 对象的 message 字段
          }
        } catch (error) {
          console.error('删除失败:', error);
          ElMessage.error('删除失败');
        }
      })
      .catch(() => {
        ElMessage.info('操作已取消');
      });
};

// 组件挂载时执行分页查询
onMounted(() => {
  findPage();
});
</script>

<style scoped>
/* 新增的样式 */
.top-section-container {
  background-color: #f9f9f9;
  padding: 1.25rem 1.25rem 0.625rem;
  border-bottom: 3px solid #409EFF;
  margin-bottom: 1.25rem;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.bottom-section-container {
  background-color: #ffffff;
  padding: 1.25rem;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  border-radius: 0.25rem;
}

/* 现有样式调整 */
.content-header {
  padding-bottom: 0.625rem;
}

.filter-container {
  box-shadow: none;
  border-bottom: none;
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

.dialog-footer {
  text-align: right;
  margin-top: 1.25rem;
}
/* 整体表格字体大小调整 */
.datatable {
  font-size: 0.875rem; /* 14px / 16 = 0.875rem */
}
</style>